package com.joey.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * 1.CountDownLatch计数器只能计算一次，而CyclicBarrier可以重置循环计数；
 * 2.CountDownLatch主要是实现1个或N个线程等待其他线程的关系；CyclicBarrier实现多个线程之间相互等待，直到所有线程都满足了条件之后，才能继续执行后续操作；
 * @Author hyy
 **/
@Slf4j

public class CyclicBarrierExample1 {

    //循环屏障线程数量是5
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(5);

    public static void main(String[] args) throws InterruptedException {
        
        ExecutorService executorService = Executors.newCachedThreadPool();

        for(int i = 0 ;i< 10;i++){
            final int threadName = i;
            Thread.sleep(1000);
            executorService.execute(() -> {
                try {
                    race(threadName);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });
        }

        executorService.shutdown();
    }

    private static void race(int threadName) throws Exception{
        Thread.sleep(1000);
        log.info("{} is ready",threadName);
        try{
            cyclicBarrier.await(2000, TimeUnit.MILLISECONDS);
        }catch (BrokenBarrierException | TimeoutException e ){
            log.warn("BrokenBarrierException",e);
        }

        log.info("{} is continue",threadName);

    }

}
